package cn.taobaoke.restful.datasource;

import cn.taobaoke.restful.exception.TBKException;
import cn.taobaoke.restful.util.Constants;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

/**
 * @author yangzuo
 * @since 2017-05-06 06:38
 */
@Aspect
// @Order(-10)
@Component
public class DynamicDataSourceAspect {

    @Before("@annotation(targetDataSource)")
    public void changeDataSource(JoinPoint joinPoint, TargetDataSource targetDataSource) throws Throwable {

        Object[] args = joinPoint.getArgs();
        if (args.length == 0) {
            throw new TBKException("[" + joinPoint.getSignature().toString() + "] 参数个数不能为0");
        }

        String databaseId = Constants.DATABASE_PREFIX + args[0]; // 实际数据源
        logger.debug("AOP Before: Change datasource to datasource [{}].", databaseId);
        if (! DynamicDataSourceContextHolder.dataSourceMap.containsKey(databaseId)) {
            throw new TBKException("数据源 ["+ databaseId +"] 尚未创建");
        }

        DynamicDataSourceContextHolder.setDataSourceType(databaseId);
    }

    @After("@annotation(targetDataSource)")
    public void restoreDataSource(JoinPoint point, TargetDataSource targetDataSource) {
        logger.debug("AOP After: Revert to default datasource [datasource].");
        DynamicDataSourceContextHolder.clearDataSourceType();
    }

    private static Logger logger = LogManager.getLogger(DynamicDataSourceAspect.class);
}
